package com.ruoyi.common.redis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ysq
 * @Date: 2024/09/12/16:54
 * @Description: 商家的位置数据已经存储在Redis中,使用Spring Data Redis来操作Redis。
 */
@Service
public class NearbyMerchantsService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 获取附近商家
     */
    public List<String> getNearbyShops(double longitude, double latitude, double radius) {
        // 设置序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        GeoOperations<String, Object> geoOps = redisTemplate.opsForGeo();

        // 获取指定半径内的店铺ID
        Circle circle = new Circle(new Point(longitude, latitude), new Distance(radius, Metrics.KILOMETERS));
        GeoResults<RedisGeoCommands.GeoLocation<Object>> results = geoOps.radius("shops", circle);

        List<String> shopIds = new ArrayList<>();
        if (results != null) {
            for (GeoResult<RedisGeoCommands.GeoLocation<Object>> result : results) {
                shopIds.add(String.valueOf(result.getContent().getName()));
                System.out.println("店铺ID: " + result.getContent().getName());
            }
        } else {
            System.out.println("没有找到附近店铺");
        }
        return shopIds;
    }
}
